package com.common.base.widget

import android.content.Context
import android.os.CountDownTimer
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import com.common.base.R
import com.common.base.utils.AppUtils.getString

/**
 * 自定义验证码按钮
 */
class VerifyCodeTextView(context: Context, attrs: AttributeSet?) : AppCompatTextView(context, attrs) {

    companion object {
        const val MAX_COUNT_DOWN = 60 * 1000L //60s
        var COUNT_DOWN_TEXT_FORMAT = "${getString(R.string.common_re_send_hint)}(%ds)"
    }

    private var mMaxCountDown = MAX_COUNT_DOWN
    private var mCountDownTextFormat = COUNT_DOWN_TEXT_FORMAT

    private val mCountDownTimer by lazy {
        object : CountDownTimer(mMaxCountDown, 1000L) {
            override fun onTick(millisUntilFinished: Long) {
                text = String.format(mCountDownTextFormat, millisUntilFinished / 1000)
            }

            override fun onFinish() {
                resetState()
            }
        }
    }

    fun setCountDownMax(max: Long): VerifyCodeTextView{
        mMaxCountDown = max
        return this
    }

    fun setCountDownTextFormat(format: String): VerifyCodeTextView{
        mCountDownTextFormat = format
        return this
    }

    fun resetState() {
        isEnabled = true
        text = getString(R.string.common_re_send_hint)
        mOnStateChangedListener?.onReEnabled()
        mCountDownTimer.cancel()
    }

    /*
        倒计时，并处理点击事件
     */
    fun startCountDown() {
        isEnabled = false
        mCountDownTimer.start()
    }

    override fun setEnabled(enabled: Boolean) {
//        setTextColor(ContextCompat.getColor(context, if (enabled) R.color.product_color else R.color.color_999999))
//        setBackgroundResource(if (enabled) R.drawable.bg_stroke_round_product7 else R.drawable.bg_stroke_round_gray7)
        super.setEnabled(enabled)
    }

    private var mOnStateChangedListener: OnStateChangedListener? = null

    fun setOnStateChangedListener(onStateChangedListener: OnStateChangedListener?) {
        mOnStateChangedListener = onStateChangedListener
    }

    interface OnStateChangedListener {
        fun onReEnabled()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        mCountDownTimer.cancel()
    }
}